// 多站点内容脚本
class MultiSiteContentScript {
  constructor() {
    this.configManager = new SiteConfigManager();
    this.currentSite = null;
    this.lastTokens = new Map(); // 存储每个站点的最后token
    this.isProcessing = false;
    this.checkInterval = 5000;
    this.checkTimer = null;
  }

  async initialize() {
    console.log('[Multi-Site Token Export] 内容脚本已加载');
    console.log('[Multi-Site Token Export] 当前域名:', window.location.hostname);
    
    // 获取当前站点的配置
    this.currentSite = await this.configManager.getSite(window.location.hostname);
    
    if (!this.currentSite) {
      console.log('[Multi-Site Token Export] 当前站点未配置，跳过');
      return;
    }

    console.log(`[Multi-Site Token Export] 检测到站点: ${this.currentSite.site_name}`);
    console.log(`[Multi-Site Token Export] 站点配置:`, this.currentSite);
    
    // 立即检查一次
    await this.checkAndSendToken();
    
    // 设置定期检查
    this.setupPeriodicCheck();
    
    // 设置storage监听
    this.setupStorageListener();
  }

  async checkAndSendToken() {
    if (this.isProcessing) return;
    
    if (!this.isExtensionContextValid()) {
      console.log('[Multi-Site Token Export] 扩展上下文已失效，停止检测');
      this.stopPeriodicCheck();
      return;
    }

    try {
      const token = AuthDataExtractor.extract(this.currentSite);
      console.log(`[Multi-Site Token Export] 检查token (${this.currentSite.site_name}):`, token ? token.substring(0, 10) + '...' : 'null');
      console.log(`[Multi-Site Token Export] 当前站点域名: ${this.currentSite.site_domain}`);
      console.log(`[Multi-Site Token Export] 上次token:`, this.lastTokens.get(this.currentSite.site_domain));
      
      if (token && token !== this.lastTokens.get(this.currentSite.site_domain)) {
        console.log(`[Multi-Site Token Export] 检测到新token (${this.currentSite.site_name}):`, token.substring(0, 10) + '...');
        
        this.isProcessing = true;
        
        const timeoutId = setTimeout(() => {
          console.error('[Multi-Site Token Export] 响应超时，标记处理完成');
          this.isProcessing = false;
        }, 10000);
        
        chrome.runtime.sendMessage({
          action: 'sendToken',
          siteName: this.currentSite.site_name,
          siteDomain: this.currentSite.site_domain,
          authType: this.currentSite.auth_type,
          authKey: this.currentSite.auth_key,
          token: token
        }, (response) => {
          clearTimeout(timeoutId);
          this.isProcessing = false;
          
          if (chrome.runtime.lastError) {
            console.error('[Multi-Site Token Export] 扩展通信错误:', chrome.runtime.lastError.message);
            return;
          }
          
          console.log('[Multi-Site Token Export] 收到后台脚本响应:', response);
          
          if (response && response.success) {
            console.log(`[Multi-Site Token Export] ✅ Token发送成功 (${this.currentSite.site_name})，停止检测`);
            this.lastTokens.set(this.currentSite.site_domain, token);
            this.stopPeriodicCheck();
            
            // 通知popup更新状态显示
            setTimeout(() => {
              chrome.runtime.sendMessage({ action: 'refreshPopup' }, () => {
                // 忽略响应，这只是一个通知消息
              });
            }, 100);
          } else {
            console.error(`[Multi-Site Token Export] ❌ Token发送失败 (${this.currentSite.site_name}):`, response?.error || '未知错误');
          }
        });
      }
    } catch (error) {
      console.error('[Multi-Site Token Export] 检查token时出错:', error);
      this.isProcessing = false;
    }
  }

  setupPeriodicCheck() {
    this.checkTimer = setInterval(() => {
      this.checkAndSendToken();
    }, this.checkInterval);
    console.log('[Multi-Site Token Export] 开始定期检查Token');
  }

  stopPeriodicCheck() {
    if (this.checkTimer) {
      clearInterval(this.checkTimer);
      this.checkTimer = null;
      console.log('[Multi-Site Token Export] 已停止定期检查');
    }
  }

  setupStorageListener() {
    window.addEventListener('storage', (event) => {
      if (this.currentSite && event.key === this.currentSite.auth_key && event.newValue) {
        console.log('[Multi-Site Token Export] 检测到storage变化');
        this.checkAndSendToken();
      }
    });
  }

  isExtensionContextValid() {
    try {
      return chrome.runtime && chrome.runtime.id;
    } catch (error) {
      return false;
    }
  }
}

// 启动
const multiSiteScript = new MultiSiteContentScript();
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => multiSiteScript.initialize());
} else {
  multiSiteScript.initialize();
} 